# shows fitting for several lambdas
# e.g.
# lambdas_fit('paiva', '0', pnorm, c(0,1))

gg_color_hue <- function(n) {
  hues = seq(15, 375, length=n+1)
  hcl(h=hues, l=65, c=100)[1:n]
}

# for one distribution, across memories

lambdas_fit <- function(filename, states, pdistr, lambda.lim, ylim=NULL, fit_test=test.distance)
{
	par(mar=c(2,4,0.1,2))

	if(identical(fit_test,test.distance)) {
		ylab <- bquote(max(abs(X[lambda] - italic(D))))
		bestfitfn <- min
	}

	colors <- gg_color_hue(2)
	color <- if(identical(pdistr,pnorm)) colors[1] else colors[2]
	label <- if(identical(pdistr,pnorm)) "N(0,1)" else "BHP"

	p <- plot
	for(s in states) {
		X <- Xstate(read(filename), s)

		lambdas <- seq(lambda.lim[1]-0.1,lambda.lim[2]+0.1,0.01)
		fits <- c()
		for(l in lambdas)
			fits <- c(fits, fit_test(power_transform(X,l), pdistr))
		bestfit <- fits == bestfitfn(fits)

		p(lambdas, fits, type='l', col=color, lwd=nchar(s), xlim=lambda.lim, ylab=ylab, cex.axis=0.8, ylim=ylim)
		points(lambdas[bestfit], fits[bestfit], col='red', pch=19, lwd=2)
		p <- lines
	}

	legend('topright', as.character(nchar(states)), title=expression(bold("memory")), col=rep(color,length(states)), lwd=nchar(states), bg='white')
}

# for one memory, across distributions

lambdas_fit2 <- function(X, lambda.lim, ylim=NULL, fit_test=test.distance)
{
	par(mar=c(2,4,0.1,2))

	if(identical(fit_test,test.distance)) {
		ylab <- bquote(max(abs(X[lambda] - italic(D))))
		bestfitfn <- min
	}

	colors <- gg_color_hue(2)
	p <- plot
	i <- 1
	for(pdistr in c(pnorm,pbhp)) {
		lambdas <- seq(lambda.lim[1]-0.1,lambda.lim[2]+0.1,0.01)
		fits <- c()
		for(l in lambdas)
			fits <- c(fits, fit_test(power_transform(X,l), pdistr))
		bestfit <- fits == bestfitfn(fits)

		p(lambdas, fits, type='l', col=colors[i], lwd=2, xlim=lambda.lim, ylab=ylab, cex.axis=0.8, ylim=ylim)
		points(lambdas[bestfit], fits[bestfit], col='red', pch=19, lwd=2)
		p <- lines
		i <- i+1
	}

	legend('topright', c("N(0,1)","BHP"), title=expression(bold("distribution")), col=colors, lwd=2, bg='white')
}

